<template>
  <el-dialog v-model="props.visible" :fullscreen="true" @update:visible="$emit('close')">
    <template #header>
        <span class="flex justify-center items-center">
          配置管理
        </span>
    </template>
    <el-card class="mb-2.5" v-show="SearchShow">
      <!-- 搜索表单 -->
      <el-form ref="searchFormRef" :model="searchForm" label-position="left">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="配置标题">
              <el-input v-model="searchForm.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配置标识">
              <el-input v-model="searchForm.key"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" :icon="Search" plain @click="handleSearch">搜索</el-button>
            <el-button :icon="RefreshRight" @click="handleSearchFormReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <!-- 数据表格 -->
      <div class="table-container">
        <div class="mb-2.5">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-button type="primary" :icon="CirclePlus" @click="openDialogForm(true)">新增</el-button>
            </el-col>
            <el-col :span="12">
              <div class="flex justify-end">
                <el-button :icon="Search" circle @click="SearchShow = !SearchShow"/>
                <el-button :icon="RefreshRight" circle @click="handleSearchFormReset"></el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="table-wrapper">
          <el-table :data="tableData" style="width: 100%;">
            <el-table-column align="center" prop="id" label="ID"></el-table-column>
            <el-table-column align="center" prop="title" label="配置标题"></el-table-column>
            <el-table-column align="center" prop="key" label="配置标识"></el-table-column>
            <el-table-column align="center" prop="value" label="配置值"></el-table-column>
            <el-table-column align="center" prop="sort" label="排序"></el-table-column>
            <el-table-column align="center" prop="type" label="组件"></el-table-column>
            <el-table-column align="center" prop="remark" label="配置说明"></el-table-column>
            <el-table-column align="center" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusInfo(scope.row.status).type">
                  {{ getStatusInfo(scope.row.status).text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template #default="scope">
                <el-button type="primary" link @click="openDialogForm(false, scope.row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <div class="py-5 px-0 flex justify-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[15, 30, 50, 100]"
                         :disabled="false" background layout="total, sizes, prev, pager, next, jumper"
                         :total="total"
                         @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </div>
      <el-dialog v-model="formShow" :title="dialogTitle" width="700">
        <el-form ref="formDataRef" class="pa-5" :rules="rules" :model="formData" label-position="right"
                 label-width="auto">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配置标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入配置标题" autocomplete="off"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配置标识" prop="key">
                <el-input v-model="formData.key" placeholder="请输入配置标识" autocomplete="off"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配置值" prop="value">
                <el-input v-model="formData.value" placeholder="请输入配置值" autocomplete="off"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input v-model="formData.sort" placeholder="请输入排序" autocomplete="off"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio :value="1">启用</el-radio>
                  <el-radio :value="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="组件">
                <el-select
                    v-model="formData.type"
                    placeholder="选择组件"
                >
                  <el-option
                      v-for="item in componentList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="配置参数">
            <el-input v-model="formData.options" type="textarea" placeholder="请输入配置参数" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="配置说明">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入配置说明" autocomplete="off"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit()">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, computed, nextTick, watch} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {RefreshRight, Search, CirclePlus} from '@element-plus/icons-vue'
import {
  getConfigListApi,
  getConfigInfoApi,
  saveConfigInfoApi,
  updateConfigInfoApi,
  deleteConfigInfoApi
} from '@/api/sysConfig'

const props = defineProps({
  group_id: Number,
  visible: Boolean
});

// 表格数据
const tableData = ref([]);
// 表格数据总数量
const total = ref(0);
// 当前分页
const currentPage = ref(1);
// 项目条数
const pageSize = ref(15);
// 是否显示搜索表单视图
const SearchShow = ref(true);
// 表单对话框
const formShow = ref(false);
// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增配置' : '编辑配置'));
// 提交表单ref
const formDataRef = ref<FormInstance>();
// 搜索表单ref
const searchFormRef = ref<FormInstance>();
// 是否新增
const isAdd = ref(false);
// 组件列表
const componentList = ref([
  {label: '文本框', value: 'input'},
  {label: '文本域', value: 'textarea'},
  {label: '下拉选择框', value: 'select'},
  {label: '单选框', value: 'radio-group'},
  {label: '图片上传', value: 'upload'},
  {label: '富文本编辑器', value: 'editor'},
]);

// 可选：定义接口以增强类型安全性
interface SearchFormTypes {
  group_id: number | null;
  title?: string;
  key?: string;
}

// 使用接口定义搜索表单
const searchForm = ref<SearchFormTypes>({
  group_id: props.group_id,
});

// 接口类型
interface FormDataTypes {
  id?: number
  title: string
  group_id: number | null
  key: string
  value: string
  type: string
  options: string
  sort: number
  status: number
  remark: string,
}

// 表单数据字段
const initForm = reactive<FormDataTypes>({
  title: '',
  group_id: null,
  key: '',
  value: '',
  type: '',
  options: '',
  sort: 1,
  status: 1,
  remark: '',
})

// 表单数据字段
const formData = ref<FormDataTypes>({...initForm})

const rules = ref<FormRules<FormDataTypes>>({
  title: [
    {required: true, message: '配置标题必填', trigger: 'change'},
  ],
  key: [
    {required: true, message: '配置标识必填', trigger: 'change'},
  ]
});

// 状态标签
const statusMap = {
  1: {type: 'primary', text: '启用'},
  0: {type: 'danger', text: '禁用'}
} as const;

const getStatusInfo = (status: number) => statusMap[status] || {type: 'info', text: '未知状态'};

// 加载表格数据
const loadTableData = async (params: { page?: number; page_size?: number } = {}) => {
  const response = await getConfigListApi({
    ...params, // 动态传递分页参数或搜索条件
    ...searchForm.value, // 拼接搜索条件
  });
  tableData.value = response.data.list;
  total.value = response.data.total;
};

// 搜索逻辑
const handleSearch = () => {
  currentPage.value = 1; // 搜索后重置到第一页
  loadTableData({page: currentPage.value, page_size: pageSize.value}); // 调用加载方法并传递分页参数
};

// 重置搜索表单
const handleSearchFormReset = () => {
  searchForm.value = {
    group_id: props.group_id,
  };
  currentPage.value = 1; // 重置后也回到第一页
  loadTableData({page: currentPage.value, page_size: pageSize.value}); // 重新加载初始数据
};

// 删除行数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除此数据吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除操作
    await deleteConfigInfoApi(row.id);
    // 刷新表格数据
    await loadTableData({page: currentPage.value, page_size: pageSize.value});
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 表格行数变化处理
const handleSizeChange = async (page: number) => {
  pageSize.value = page;
  await loadTableData({page: currentPage.value, page_size: pageSize.value})
}

// 分页变化处理
const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage;
  await loadTableData({page: currentPage.value, page_size: pageSize.value})
};

// 打开对话表单
const openDialogForm = async (isNew: boolean, row?: { id: number }) => {
  formShow.value = true; // 显示对话框
  isAdd.value = isNew;

  formData.value = {...initForm}
  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });

  if (!isAdd.value) {
    // 编辑时获取配置信息
    const response = await getConfigInfoApi(row.id);
    formData.value = response.data
  }
};

// 关闭对话表单
const handleClose = () => {
  formShow.value = false;
}

// 提交配置表单
const handleSubmit = async () => {
  if (!formDataRef.value) return;

  // 校验表单
  await formDataRef.value.validate();

  // 配置分组ID
  formData.value.group_id = props.group_id;

  // 判断是否为新增或更新
  const isUpdate = !!formData.value.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateConfigInfoApi(formData.value.id, formData.value);
    ElMessage.success('更新成功');
  } else {
    // 新增操作
    await saveConfigInfoApi(formData.value);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新表格数据
  handleClose();
  await loadTableData({page: currentPage.value, page_size: pageSize.value});
};

// 监听 visible 属性的变化
watch(() => props.visible, (newValue) => {
  console.log(newValue);
  if (newValue === true) {
    searchForm.value.group_id = props.group_id;
    // 当对话框变为可见时执行的操作
    loadTableData({page: currentPage.value, page_size: pageSize.value});
  }
});
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}
</style>